<template>
    <div class="main">
        <div class="search-bar">
            <el-row style="margin-bottom: 20px;">
                <el-col :span="24">
                    <el-breadcrumb :separator-icon="ArrowRight">
                        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
                        <el-breadcrumb-item>系统管理</el-breadcrumb-item>
                        <el-breadcrumb-item>用户管理</el-breadcrumb-item>
                    </el-breadcrumb>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="12">
                    <el-form :inline="true" :model="formInline" class="demo-form-inline">
                        <el-form-item label="用户名">
                            <el-input v-model="searchForm.userName_like" placeholder="" clearable />
                        </el-form-item>
                        <el-form-item label="邮箱">
                            <el-input v-model="searchForm.email_like" placeholder="" clearable />
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="onSubmit">搜索</el-button>
                        </el-form-item>
                    </el-form>
                </el-col>
                <el-col :span="6" :offset="6">
                    <div class="button-group">
                        <el-button type="success" @click="handleAdd()">新增用户</el-button>
                        <el-button type="danger" @click="handleBatchDelete()">批量删除</el-button>
                    </div>
                </el-col>
            </el-row>


        </div>
        <div class="table-view">
            <el-table :data="tableData" :border="true" style="width: 100%" @selection-change="handleSelectionChange">
                <el-table-column label="全选" width="80" type="selection"></el-table-column>
                <el-table-column label="用户姓名" prop="userName" width="200"></el-table-column>
                <el-table-column label="用户角色" prop="role" width="200">
                    <template #default="scope">
                        <el-tag>{{ scope.row.role === '1' ? '超级管理员' : '管理员' }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="邮箱" prop="email" width="300"></el-table-column>
                <el-table-column label="锁定状态" prop="isLocked" width="200">
                    <template #default="scope">
                        <el-switch v-model="scope.row.isLocked"
                            style="--el-switch-on-color: #ff4949; --el-switch-off-color: #13ce66" active-text="锁定"
                            inactive-text="未锁定" />
                    </template>
                </el-table-column>
                <el-table-column label="创建时间" prop="createTime" width="200"></el-table-column>
                <el-table-column label="操作">
                    <template #default="scope">
                        <el-button @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                        <el-popconfirm width="220" :icon="InfoFilled" icon-color="#626AEF"
                            :title="'是否要删除用户: '+scope.row.userName" @cancel="onCancel" @confirm="handleDelete(scope.$index, scope.row)">
                            <template #reference>
                                <el-button type="danger">删除</el-button>
                            </template>
                            <template #actions="{ confirm, cancel }">
                                <el-button @click="cancel">取消</el-button>
                                <el-button type="primary" :disabled="!clicked" @click="confirm">
                                    确认
                                </el-button>
                            </template>
                        </el-popconfirm>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div class="pagination-container">
            <el-pagination background layout=" prev, pager, next, sizes, total" :page-size="page._limit"
                :page-sizes="[5, 10, 15, 20]" :total="page.total" @size-change="handleSizeChange"
                @current-change="handleCurrentChange">
            </el-pagination>
        </div>
        <!-- dialog -->
        <el-dialog v-model="dialogFormVisible" :title="title" width="500">
            <el-form :model="form" label-width="auto">
                <el-form-item label="用户名" :label-width="formLabelWidth" label-position="left">
                    <el-input v-model="userForm.userName" autocomplete="off" />
                </el-form-item>
                <el-form-item label="密码" :label-width="formLabelWidth" label-position="left">
                    <el-input v-model="userForm.password" autocomplete="off" />
                </el-form-item>
                <el-form-item label="确认密码" :label-width="formLabelWidth" label-position="left">
                    <el-input v-model="userForm.password" autocomplete="off" />
                </el-form-item>
                <el-form-item label="邮箱" :label-width="formLabelWidth" label-position="left">
                    <el-input v-model="userForm.email" autocomplete="off" />
                </el-form-item>
                <el-form-item label="角色" :label-width="formLabelWidth" label-position="left">
                    <el-select v-model="userForm.role" placeholder="请选择角色">
                        <el-option label="超级管理员" value="1" />
                        <el-option label="管理员" value="2" />
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogFormVisible = false">取消</el-button>
                    <el-button type="primary" @click="handleInsertOrUpdate()">提交</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang='ts'>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import type { User } from '../../common/index'
import axios from 'axios'
import { ArrowRight } from '@element-plus/icons-vue'

/**
 *  ----- 初始化表格数据 ------
 */
const tableData = ref<User[]>([])
onMounted(() => {
    let { _page, _limit } = page.value
    getDate({ _page, _limit }) // 初始加载第一页数据
})

//获得数据
const getDate = (params: Object) => {
    axios.get("http://localhost:3000/sys_user", { params }).then(response => {
        tableData.value = response.data
        page.value.total = Number.parseInt(response.headers['x-total-count'])
    }).catch(error => {
        console.error("获取用户数据失败:", error)
        ElMessage.error('获取用户数据失败')
    })
}

/**
 *  ----- 搜索用户 ------
 */
const searchForm = ref({
    userName_like: '',
    email_like: ''
})
const onSubmit = () => {
    getDate({
        _page: page.value._page,
        _limit: page.value._limit,
        ...searchForm.value
    })
}

/**
 * ----- 用户管理操作 -----
 */
const dialogFormVisible = ref(false)
const userForm = ref<User>({
    userName: '',
    password: '',
    email: '',
    isLocked: false,
    role: '1',
    createTime: new Date().toISOString()
})

//清空表单
const cleanUserForm = () => {
    userForm.value = { userName: '', password: '', email: '', isLocked: false, role: '1', createTime: new Date().toISOString() } // 重置表单
}

//新增用户
const title = ref('新增用户')
const handleAdd = () => {
    title.value = '新增用户'
    cleanUserForm(); // 重置表单
    dialogFormVisible.value = true;
}
//编辑用户
const handleEdit = (index: number, row: any) => {
    title.value = '编辑用户'
    cleanUserForm(); // 重置表单
    userForm.value = { ...row } // 复制当前行数据到表单
    dialogFormVisible.value = true;
}

//提交数据
const handleInsertOrUpdate = () => {
    if (title.value === '新增用户') {
        //ajax 新增用户
        axios.post("http://localhost:3000/sys_user", userForm.value).then(response => {
            console.log(response.data)
            ElMessage.success('新增用户成功')
            dialogFormVisible.value = false
            cleanUserForm() // 重置表单
            getDate(page.value) // 重新获取数据
        }).catch(error => {
            console.error("添加用户失败:", error)
            ElMessage.error('添加用户失败')
        })
        return;
    }

    //ajax 编辑用户
    axios.put(`http://localhost:3000/sys_user/${userForm.value.id}`, userForm.value).then(response => {
        console.log(response.data)
        ElMessage.success('编辑用户成功')
        dialogFormVisible.value = false
        cleanUserForm() // 重置表单
        getDate(page.value) // 重新获取数据
    }).catch(error => {
        console.error("编辑用户失败:", error)
        ElMessage.error('编辑用户失败')
    })


}

//删除用户
const clicked = ref(false)
function onCancel() {
  clicked.value = true
}
const handleDelete = (index: number, row: any) => {
    axios.delete(`http://localhost:3000/sys_user/${row.id}`).then(response => {
        console.log(response.data)
        ElMessage.success('删除用户成功')
        getDate(page.value) // 重新获取数据
    }).catch(error => {
        console.error("删除用户失败:", error)
        ElMessage.error('删除用户失败')
    })
}

//删除多个用户
const selectedRows = ref([]);
 
const handleSelectionChange = (val:any) => {
  selectedRows.value = val; // val是当前选中行的数组
  console.log(selectedRows.value);
}

const handleBatchDelete = () => {
    // 获取选中的行
    if (selectedRows.value.length === 0) {
        ElMessage.warning('请先选择要删除的用户')
        return
    }
    // 批量删除请求
    const deletePromises = selectedRows.value.map(row => axios.delete(`http://localhost:3000/sys_user/${row.id}`))
    Promise.all(deletePromises).then(() => {
        ElMessage.success('批量删除用户成功')
        getDate(page.value) // 重新获取数据
    }).catch(error => {
        console.error("批量删除用户失败:", error)
        ElMessage.error('批量删除用户失败')
    })
}

/**
 * ----- 分页功能 -----
 */
const page = ref({
    _page: 1,
    _limit: 5,
    total: 0
})

const handleSizeChange = (size: number) => {
    page.value._limit = size
    getDate(page.value) // 重新获取数据
}
const handleCurrentChange = (currentPage: number) => {
    page.value._page = currentPage
    getDate(page.value) // 重新获取数据
}
</script>

<style scoped>
.main {
    background-color: #fff;
    width: 100%;
    height: 100%;
}

.search-bar {
    padding: 20px;
}

.search-bar .el-form .el-form-item {
    margin: auto;
    margin-right: 20px;
}

.pagination-container {
    padding: 20px;
    display: flex;
    justify-content: center;
}
</style>